package logic

import (
	"context"
	"zhihu/models/mysql"
	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProblemListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProblemListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProblemListLogic {
	return &ProblemListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProblemListLogic) ProblemList(in *zhihurpc.ProblemListRequest) (*zhihurpc.ProblemListResponse, error) {
	// todo: add your logic here and delete this line
	var problems []mysql.Problem
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	mysql.DB.Debug().Where("problem_desc like ?", "%"+in.ProblemDesc+"%").Offset(int(offset)).Limit(int(pageSize)).Find(&problems)

	var problemLists []*zhihurpc.ProblemList
	for _, problem := range problems {
		list := zhihurpc.ProblemList{
			ProblemImage: problem.ProblemImage,
			ProblemDesc:  problem.ProblemDesc,
			UserId:       int64(problem.UserId),
			Id:           int64(problem.ID),
		}
		problemLists = append(problemLists, &list)
	}
	return &zhihurpc.ProblemListResponse{
		List: problemLists,
	}, nil
}
